import request from "@/axios";
import store from "@/store/index";
export default ({
    namespaced:true,
    state: {
         LoginState:false,
         User:JSON.parse(localStorage.getItem('User'))|| null,
    },
    getters: {},
    mutations: {
        //开启登录框
        LOGINSTATEON:(state)=>state.LoginState=true,
        //关闭登录框
        LOGINSTATEDOWN:(state)=>state.LoginState=false,
         
        //修改用户信息
        SETUSER:(state,data) =>{
            state.User=data
            localStorage.setItem('User',JSON.stringify(data))
        },
      
        
    },
    actions: {

        //登录
        async loginIn(context,user){
            try{
               let res= await request.post('/api/user/login',user)      
               if(res.data.code==200){         
                    localStorage.setItem("token",res.data.data.token) 
                    context.commit('SETUSER',res.data.data.user) 
                    context.commit('LOGINSTATEDOWN')     //关闭登录框
                    store.dispatch('Init/checkToken')   //1:检验token  2:登录成功后会初始化一些信息            
                }
                return res.data 
            }
            catch (error){return {code:400,message:error}}
             
                     
           },
        //修改
        async editUser(context,user){
            try{
                let res= await request.post('/api/user/edit',user)   
                 if(res.data.code==200)
                     context.commit('SETUSER',res.data.data)                
                return  res.data   
             }
             catch (error){return {code:400,message:error}}       
           },
          //修改
        async editPassword({dispatch},user){
            try{
                let res= await request.post('/api/user/editPassword',user)              
                return  res.data   
             }
             catch (error){return {code:400,message:error}}       
           },
         //注册
         async createUser(context,user){
            try{
                let res= await request.post('/api/user/register',user)        
                return  res.data    
             }
             catch (error){return {code:500,message:error} }          
           },
        //退出
        async loginOut(context,uid){
            try{
                 let res
                  if(uid) res = await request.get('/api/user/logout',{params:{uid}})
                  else res ={code:200,message:'成功'}
             
                 localStorage.removeItem("User")
                 localStorage.removeItem('token')
                 context.commit('SETUSER',null) 
                 return res.data         
          }catch(error){
            return {message:error,code:400}
          }


        }
           
    }//action结束

    
})

